package com.ledim.fragment;

import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.MainActivity;
import com.ledim.activity.RoomActivity;
import com.ledim.activity.UserLoginActivity;
import com.ledim.adapter.LedimRoomListAdapter;
import com.ledim.adapter.base.LedimBaseListAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.LedimChatMsgBean;
import com.ledim.bean.RoomListResponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.fragment.base.LedimBaseListFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.itf.LedimDoubleClickListener;
import com.ledim.ledimview.LedimUserIconView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.Key;
import java.util.HashMap;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ccx on 16/6/20.
 * 首页放映厅Fragment
 */
public class LedimRoomFragment extends LedimBaseListFragment
        implements MainActivity.DoubleTabClickLister {

    /**
     * 我的放映厅容器 ListView header
     */
    private View headerView;
    /**
     * 我的放映厅容器 包括listview header上的
     */
    private FrameLayout fl_roomtype, fl_header_roomtype;
    /**
     * 是否悬浮状态
     */
    private boolean isStick = false;
    private int LIMIT_OFFSET;
    private int[] size = new int[2];
    /**
     * 放映厅type类型View
     */
    private RadioGroup rg_room_type;
    private FrameLayout fl_room_type;
    private int CALL_ROO_TYPE = ConstantUtil.ROOM_RECOMMEND_TYPE;
    private View ll_room_card, iv_create_room;
    private SimpleDraweeView iv_room_pic;
    private LedimUserIconView iv_room_creater;
    private TextView room_creater_name, tv_room_videoname, tv_coin_counts, tv_chat_msg;
    private View ll_play_state, ll_chat_msg;
    private ImageView iv_playing_state;
    private View view_room_bg;
    private View mFocusChangeState;
    private rx.Observer mObsevers;

    @Override
    protected LedimBaseListAdapter getAdapter() {
        return new LedimRoomListAdapter(mActivity);
    }

    @Override
    protected void getDatas() {
        if (mObsevers == null) {
            mObsevers = new LedimHttpObserver<RoomListResponse>() {
                @Override
                public void onCompleted() {
                    super.onCompleted();
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    setServerDataError();
                    initMyRoomCard(null);
                    LogUtil.e("getDatas====" + e.getMessage());
                }

                @Override
                public void onNext(RoomListResponse roomBaseListResponse) {
                    if (roomBaseListResponse != null && roomBaseListResponse.success) {
                        initMyRoomCard(roomBaseListResponse.ext);
                        initTotalPages(roomBaseListResponse.paged.total);
                        setDatas(roomBaseListResponse.data, roomBaseListResponse.paged.more);
                    } else {
                        setServerDataError();
                    }
                }
            };
        }
        LedimApiServiceFactory.createService(ApiService.class)
                              .getLedimRooms(CALL_ROO_TYPE, mLoadPage + 1, getPageSize())
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io()).subscribe(mObsevers);
    }

    @Override
    protected void initContentView(View view, Bundle saveInstanceState) {
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText(R.string.ledim_room);
        tv_title.setOnTouchListener(new LedimDoubleClickListener() {
            @Override
            public void onDoubleClick(View view) {
                mAdapterView.setSelection(0);
                ((ListView) mAdapterView).setSelectionAfterHeaderView();
                mAdapterView.smoothScrollToPosition(0);
            }
        });
        fl_roomtype = (FrameLayout) view.findViewById(R.id.fl_roomtype);
        // 临界点距离屏幕上方高度
        LIMIT_OFFSET = getResources().getDimensionPixelSize(R.dimen.title_height) +
                mActivity.tintManager.getConfig().getStatusBarHeight();//
        initHeaderView();
    }

    private void hanlerTypeView() {
        if (getItems() != null && getItems().size() > 2) {
            fl_header_roomtype.getLocationInWindow(size);

            if (!isStick) { // 没有悬浮 size[1] < LIMIT_OFFSET && size[1] != 0
                if (size[1] < LIMIT_OFFSET && size[1] != 0) { // 达到悬浮位置，
                    // 移除header中的 room_type，添加到悬浮框中
                    fl_header_roomtype.removeView(fl_room_type);
                    fl_roomtype.addView(fl_room_type);
                    //headerView.setVisibility(View.GONE);
                    isStick = true;
                }
            } else { // 悬浮中
                if (size[1] > LIMIT_OFFSET) {
                    fl_roomtype.removeView(fl_room_type);
                    fl_header_roomtype.addView(fl_room_type);
                    // headerView.setVisibility(View.VISIBLE);
                    isStick = false;
                }
            }
        }
    }

    /**
     * 初始化Listview头部view
     */
    private void initHeaderView() {
        headerView = getBaseActivity().getLayoutInflater()
                                      .inflate(R.layout.ledim_room_listviewhead, null);
        ((ListView) mAdapterView).addHeaderView(headerView);
        fl_header_roomtype = (FrameLayout) headerView.findViewById(R.id.fl_header_roomtype);
        iv_create_room = headerView.findViewById(R.id.iv_create_room);
        ll_room_card = headerView.findViewById(R.id.ll_room_card);
        ll_room_card.setVisibility(View.GONE);
        view_room_bg = headerView.findViewById(R.id.view_room_bg);
        ll_chat_msg = headerView.findViewById(R.id.ll_chat_msg);
        tv_chat_msg = (TextView) headerView.findViewById(R.id.tv_chat_msg);
        //小红点
        mFocusChangeState = headerView.findViewById(R.id.focus_change_state);
        if (!LedimSpUtils.isLogin()) {
            view_room_bg.setVisibility(View.GONE);
            iv_create_room.setVisibility(View.VISIBLE);
            iv_create_room.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LedimSpUtils.isLogin()) {
                        LedimFunctionUtils.showLoginDialog(getActivity());
                    } else {
                        Intent intent = new Intent(getActivity(), RoomActivity.class);
                        startActivity(intent);
                    }
                }
            });
        }
        iv_room_creater = (LedimUserIconView) headerView.findViewById(R.id.iv_room_creater);
        iv_room_pic = (SimpleDraweeView) headerView.findViewById(R.id.iv_room_pic);
        tv_room_videoname = (TextView) headerView.findViewById(R.id.tv_room_videoname);
        room_creater_name = (TextView) headerView.findViewById(R.id.room_creater_name);
        tv_coin_counts = (TextView) headerView.findViewById(R.id.tv_coin_counts);
        ll_play_state = headerView.findViewById(R.id.ll_play_state);
        iv_playing_state = (ImageView) headerView.findViewById(R.id.iv_playing_state);
        rg_room_type = (RadioGroup) headerView.findViewById(R.id.rg_room_type);
        fl_room_type = (FrameLayout) headerView.findViewById(R.id.fl_room_type);
        rg_room_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                LogUtil.e("ccx onCheckedChanged checkedId==" + checkedId);
                if (checkedId == R.id.rb_room_commond) {
                    if (CALL_ROO_TYPE != ConstantUtil.ROOM_RECOMMEND_TYPE) {
                        CALL_ROO_TYPE = ConstantUtil.ROOM_RECOMMEND_TYPE;
                        pullRefresh();
                        reportExpose();
                    }
                } else if (checkedId == R.id.rb_room_new) {
                    if (CALL_ROO_TYPE != ConstantUtil.ROOM_NEW_TYPE) {
                        CALL_ROO_TYPE = ConstantUtil.ROOM_NEW_TYPE;
                        pullRefresh();
                        reportExpose();
                    }
                } else if (checkedId == R.id.rb_room_follow) {
                    if (LedimSpUtils.isLogin()) {
                        if (CALL_ROO_TYPE != ConstantUtil.ROOM_FOLLOW_TYPE) {
                            CALL_ROO_TYPE = ConstantUtil.ROOM_FOLLOW_TYPE;
                            pullRefresh();
                            reportExpose();
                        }
                    } else {

                        LedimFunctionUtils.showLoginDialog(getActivity(), new LedimDialogClickListner() {
                            private boolean goLogin = false;

                            @Override
                            public void onClickPositive(View view) {
                                goLogin = true;
                                Bundle mBundle = new Bundle();
                                mBundle.putInt(ConstantUtil.REQUSET, ConstantUtil.LOGIN_REQUEST);
                                goToOthersForResult(UserLoginActivity.class, mBundle, ConstantUtil.LOGIN_REQUEST);
                            }

                            @Override
                            public void onClickNegative(View view) {

                            }

                            @Override
                            public void onDismiss() {
                                if (!goLogin) {
                                    checkPreRoomType();
                                }
                            }
                        });
                    }
                }

            }
        });
        mAdapter.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
                hanlerTypeView();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ConstantUtil.LOGIN_REQUEST) {
            if (resultCode == ConstantUtil.LOGIN_CANCEL_RESPONSE) {
                checkPreRoomType();
            } else if (resultCode == ConstantUtil.LOGIN_SUCCESS_RESPONSE) {
                CALL_ROO_TYPE = ConstantUtil.ROOM_FOLLOW_TYPE;
                pullRefresh();
            }
        }
    }

    /**
     * 选中之前的roomType
     */
    private void checkPreRoomType() {
        switch (CALL_ROO_TYPE) {
            case ConstantUtil.ROOM_RECOMMEND_TYPE:
                ((RadioButton) rg_room_type.findViewById(R.id.rb_room_commond)).setChecked(true);
                break;
            case ConstantUtil.ROOM_NEW_TYPE:
                ((RadioButton) rg_room_type.findViewById(R.id.rb_room_new)).setChecked(true);
                break;
            case ConstantUtil.ROOM_FOLLOW_TYPE:
                ((RadioButton) rg_room_type.findViewById(R.id.rb_room_follow)).setChecked(true);
                break;
        }
    }

    /**
     * 初始化我的放映厅卡片
     */
    private void initMyRoomCard(final ChatRoomBean room) {
        if (room == null) {
            iv_create_room.setVisibility(View.VISIBLE);
            view_room_bg.setVisibility(View.GONE);
            ll_room_card.setVisibility(View.GONE);
            ll_chat_msg.setVisibility(View.GONE);
            iv_create_room.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LedimFunctionUtils.showLoginDialog(getActivity());
                }
            });
            return;
        }
        ll_room_card.setVisibility(View.VISIBLE);
        iv_create_room.setVisibility(View.GONE);
        tv_coin_counts.setText(room.user.coin);
        //holder.tv_room_time.setText(room.);
        ll_chat_msg.setVisibility(View.GONE);
        if (room.user.avatar != null && !TextUtils.isEmpty(room.user.avatar.thumb)) {
            iv_room_creater.setUserIcon(room.user.userId, room.user.status, room.user.avatar.thumb, true);
        } else {
            iv_room_creater.setUserIcon(room.user.userId, room.user.status, "", true);
        }
        //设置小红点
        if (room.isChange == 0) {
            mFocusChangeState.setVisibility(View.GONE);
        } else {
            mFocusChangeState.setVisibility(View.VISIBLE);
        }
        room_creater_name.setText(room.user.nickname);
        GradientDrawable myGrad = (GradientDrawable) ll_play_state.getBackground();
        if (room.status == 1) {
            // view_room_bg.setVisibility(View.VISIBLE);
            headerView.findViewById(R.id.ll_playend_view).setVisibility(View.GONE);
            if (room.cover != null && room.cover.thumb != null &&
                    room.cover.thumb.length() > 0) {
                FrescoUtil.loadUrl(room.cover.thumb, iv_room_pic);
            }
            myGrad.setColor(getResources().getColor(R.color.color_white_71percent));
            iv_playing_state.setImageResource(R.drawable.room_playing_icon);
            ll_room_card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IVideo roomVideo = new IVideo();
                    roomVideo.setmVid(0);
                    LetvSDK.getInstance().playRoom(getActivity(), roomVideo, room, true, false);
                }
            });
            if (room.current != null && room.current.length() > 0 && !room.current.equals("null")) {
                tv_room_videoname.setText(room.current);
            } else {
                tv_room_videoname.setText("洗脑循环中");
            }
            if (room.history != null && room.history.size() > 0) {
                StringBuilder msgs = new StringBuilder();
                for (LedimChatMsgBean msgBean : room.history) {
                    LedimChatMsgBean chatMsgBean = msgBean.getRealChatMsgBean();
                    switch (msgBean.type) {
                        case ConstantUtil.ChatType.join:
                            msgs.append(chatMsgBean.user.nickname + "闪亮登场了~");
                            break;
                        case ConstantUtil.ChatType.text:
                            msgs.append(Html.fromHtml(
                                    chatMsgBean.user.nickname + ": " + chatMsgBean.message));
                            break;
                        case ConstantUtil.ChatType.coin:
                            msgs.append(Html.fromHtml(
                                    chatMsgBean.user.nickname + "  打赏了" + chatMsgBean.coin +
                                            "个金币"));
                            break;
                        case ConstantUtil.ChatType.icon:
                            msgs.append(Html.fromHtml(chatMsgBean.user.nickname + "发送了一个图片表情"));
                            break;
                    }
                    msgs.append("    ");

                }
                if (!TextUtils.isEmpty(msgs)) {
                    tv_chat_msg.setText(msgs.toString());
                    ll_chat_msg.setVisibility(View.VISIBLE);
                    tv_chat_msg.setTextColor(LedimFunctionUtils.getRandomColor(getActivity()));
                }
            }
        } else {
            view_room_bg.setVisibility(View.GONE);
            headerView.findViewById(R.id.ll_edit_myroom)
                      .setOnClickListener(new View.OnClickListener() {
                          @Override
                          public void onClick(View v) {
                              Intent intent = new Intent(getActivity(), RoomActivity.class);
                              intent.putExtra(RoomActivity.ROOM_ID, room);
                              intent.putExtra(RoomActivity.MY_ROOM_FLAG, true);
                              startActivity(intent);
                          }
                      });
            tv_room_videoname.setText("放映结束");
            myGrad.setColor(getBaseActivity().getResources()
                                             .getColor(R.color.color_white_72percent));
            headerView.findViewById(R.id.ll_playend_view).setVisibility(View.VISIBLE);
            // ll_room_state.setBackgroundResource(R.drawable.room_stop_bg);
            iv_playing_state.setImageResource(R.drawable.room_stop_icon);
            iv_room_pic.setImageResource(R.drawable.room_stopplay_bg);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ledimroom;
    }

    @Override
    public void onTabDoubleClick() {
        if (mAdapterView != null) {
            pullRefresh();
        }
    }

    private boolean mFirstStart = true;

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden() && !mFirstStart) {
            reportExpose();
            pullRefresh();
        }
        mFirstStart = false;
    }

    private void reportExpose() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Key.Type.name(), "room");
        if (CALL_ROO_TYPE == ConstantUtil.ROOM_NEW_TYPE) {
            params.put("tabName", "newtab");
        } else if (CALL_ROO_TYPE == ConstantUtil.ROOM_RECOMMEND_TYPE) {
            params.put("tabName", "recommendTab");
        } else {
            params.put("tabName", "follow");
        }
        LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.ROOM_PAGE_CODE, EventType.Expose, params);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            reportExpose();
            pullRefresh();
        } else {
            if (getAdapter() != null) {
                ((LedimRoomListAdapter) getAdapter()).postRoomExposeEvent();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //上传卡片曝光统计事件
        if (!isHidden() && getAdapter() != null) {
            ((LedimRoomListAdapter) mAdapter).postRoomExposeEvent();
        }
    }

    @Override
    protected boolean needFeedBack() {
        return true;
    }
}
